package db

import (
	"cr.org/model"
	"errors"
	"fmt"
	"gorm.io/gorm"
)

func Run() {
	type vector[T any] []T

	list := vector[interface{}]{
		&model.User{},
		&model.AiDrawT{},
		&model.AiModelsT{},
		&model.MapUserDrawThumbsUp{},
	}
	// 初始化数据库表结构
	for _, item := range list {
		if !db.Migrator().HasTable(item) {
			err := db.AutoMigrate(item)
			if err != nil {
				panic(fmt.Errorf("初始化数据库表结构异常: %v", err.Error()))
			}
		}
	}
	initUser()
}

func initUser() {
	var (
		err error
	)
	var d model.User
	if err = db.Where("user_id = ?", model.RootId).First(&d).Error; errors.Is(err, gorm.ErrRecordNotFound) {
		err = db.Create(model.RootUser).Error
		if err != nil {
			panic(fmt.Sprintf("导入初始化用户信息时发生错误：%v", err))
		}
	}
}
